package com.example.listviewtest;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;

public class AnimalAdapter extends ArrayAdapter {
    int animalResourceId;

    public AnimalAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Animal> objects) {
        super(context, resource, objects);
        animalResourceId = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Animal animal = (Animal) getItem(position);
        ViewHolder viewHolder = new ViewHolder();
        View view;
        if(convertView == null){
            view = LayoutInflater.from(getContext()).inflate(animalResourceId,parent,false);//这个代码很常用，需要认真看看源码，最后的boolean有什么用。
            viewHolder.imageView = view.findViewById(R.id.imageView);
            viewHolder.textView = view.findViewById(R.id.textView);
            view.setTag(viewHolder);//view中储存该控件的组件
        }else{
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();//获取控件
        }
        viewHolder.imageView.setImageResource(animal.getPicID());
        viewHolder.textView.setText(animal.getName());
        return view;
    }
    //使用一个内部类，这样里面的组件直接就示例
    class  ViewHolder{
        ImageView imageView ;
        TextView  textView ;
    }
}
